from http.client import responses

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.urls import reverse
from django.http import JsonResponse, HttpResponse, HttpResponseForbidden, HttpResponseNotFound
from django.shortcuts import render, redirect
from django.views import View

from xiaoyu_mall.apps.users.models import *
from xiaoyu_mall.utils.validators import *

# Create your views here.

class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')
    def post(self, request):
        #获取用户提交的数据
        username = request.POST.get("username")
        password = request.POST.get("password")
        password2 = request.POST.get("password2")
        mobile = request.POST.get("mobile")
        allow = request.POST.get("allow")
        print(username, password, password2, mobile, allow)
        # 数据验证
        # 用户名是否唯一
        is_username = TbUsers.objects.filter(username=username).exists()
        # 手机号是否唯一
        is_mobile = TbUsers.objects.filter(mobile=mobile).exists()

        result = [check_info(username,r"^[a-zA-Z0-9_-]{5,20}$"),
                  check_info(password, r"^[0-9A-Za-z]{8,20}$"),
                  check_info(mobile, r"^1[3-9]\d{9}$"),password2 == password,
                  allow == 'on',not is_username,not is_mobile
                  ]
        print(result)
        # username, password, password2, mobile, allow都为真,all返回真
        if all([username, password, password2, mobile, allow]):
            if all(result):
                try:
                    # 注册用户
                    TbUsers.objects.create_user(username=username, password=password, mobile=mobile)
                    # 跳转登录界面
                    return redirect(reverse('users:login'))
                except:
                    return render(request, 'register.html')
            else:
                return render(request, 'register.html')
        else:
            # 返回注册界面
            return render(request, 'register.html')

# 验证用户名
def check_username(request,username):
    # print(request.GET)
    # username = request.GET.get('username',"")
    res = TbUsers.objects.filter(username=username).exists()
    if res == True:
        return JsonResponse({
            "code": -100,
            "msg": "用户名不可用"
        })
    else:
        return JsonResponse({
            "code": 100,
            "msg": "用户名可用"
        })


def check_phone(request,phone):
    res = TbUsers.objects.filter(mobile=phone).exists()
    if res == True:
        return JsonResponse({
            "code": -100,
            "msg": "手机号不可用"
        })
    else:
        return JsonResponse({
            "code": 100,
            "msg": "手机号可用"
        })


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')
    def post(self,request):
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
        # 校验参数
        if not all([username, password]):
            return HttpResponseForbidden('缺少必传参数')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return HttpResponseForbidden('请输入正确的用户名或手机号')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('密码最少8位，最长20位')
        # 认证登录用户
        user = authenticate(username=username, password=password)
        # 验证失败
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '账号或密码错误'})
        # 登录，写入session
        login(request, user)
        # 如果没选择了记住我
        if remembered != 'on':
            request.session.set_expiry(0)  # 没有记住用户，浏览器会话结束后就过期
        else:
            request.session.set_expiry(None)  # 记住用户 None表示两周后过期
        # 跳转到首页
        response = redirect(reverse('contents:home'))
        # 登录时用户名写入到cookie，有效期14天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response


class LogoutView(View):
    def get(self,request):
        # 清除状态保持信息
        logout(request)
        # 响应结果 重定向到首页
        response = redirect(reverse('contents:home'))
        # 删除cookie中的用户名
        response.delete_cookie('username')
        return response


class UserInfoView(LoginRequiredMixin,View):
    def get(self, request):
        """提供用户中心页面"""
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            # 'email_active': request.user.email_active
        }
        return render(request, 'user_center_info.html', context=context)


class UserOrderInfoView(View):
    def get(self, request, page_num):
        """提供我的订单页面"""
        user = request.user
        # 查询订单
        orders = user.orderinfo_set.all().order_by("-create_time")
        # 遍历所有订单
        for order in orders:
            # 绑定订单状态
            order.status_name = OrderInfo.ORDER_STATUS_CHOICES[
                order.status - 1][1]
            # 绑定支付方式
            order.pay_method_name = OrderInfo.PAY_METHOD_CHOICES[
                order.pay_method - 1][1]
            order.sku_list = []
            # 查询订单商品
            order_goods = order.skus.all()
            # 遍历订单商品
            for order_good in order_goods:
                sku = order_good.sku
                sku.count = order_good.count
                sku.amount = sku.price * sku.count
                order.sku_list.append(sku)
        # 分页
        page_num = int(page_num)
        try:
            paginator = Paginator(orders, constants.ORDERS_LIST_LIMIT)
            page_orders = paginator.page(page_num)
            total_page = paginator.num_pages
        except EmptyPage:
            return HttpResponseNotFound('订单不存在')
        context = {
            "page_orders": page_orders,
            'total_page': total_page,
            'page_num': page_num,
        }
        return render(request, "user_center_order.html", context)


def use_cookie(request):
    request.session["hello"] = "world"
    # 设置cookie
    response = HttpResponse(content_type='text/html',content=b"hello world")
    response.set_cookie("name","tom",max_age=20000)
    return response


def get_cookie(request):
    # name = request.COOKIES.get('hello',"session")
    # print(name)
    print(request.session.get("hello"))
    del request.session["hello"]
    response = HttpResponse(content_type='text/html',content=b"hello world")
    response.delete_cookie("name")
    return response
def hllo():
    pass